<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * date: 2021-06-03 18:30:49
 * @LastEditors: Sam
 * @LastEditTime: 2023-02-15 14:36:28
 */


namespace app\admin\controller;
use app\admin\model\ {User,Notice as NoticeModel,NoticeType,Attach};
use think\facade\Db;
use app\common\BaseController;
use app\common\api\Esearch;

/**
 * 资讯管理
 * @author Sam
 * @date 2022-04-26
 */
class Notice extends BaseController{
    
    /**
     * 列表
     * @author Sam
     * @date 2022-04-26
     */
    public function index() {

        // $nacos = \app\common\support\Nacos::get_instance();
        // dump(get_config('name'));die;
      
    //     try {
        
    //         $es_client = Esearch::getEslasticInstance();
   
      
      
    //         $es_client->create_index('article',[
    //                 'settings' => [
    //                     'number_of_shards' => 3, # 分片数量
    //                     'number_of_replicas' => 2, # 副本数量
    //                     'index' =>[
    //                         'analysis' => [
    //                             'analyzer' => [
    //                                 'default' => [
    //                                     'type' => 'ik_smart'
    //                                 ]
    //                             ]
    //                         ]
    //                     ]
    //                 ],
    //                 'mapping' => [
    //                     'properties' =>[
                       
    //                         'id'    => [
    //                             'type' => 'long'
    //                         ],
    //                         'thumb' => [
    //                             'type' => 'text',
    //                         ],
    //                         'title' => [
    //                             'type' => 'text',
    //                         ],
    //                         'is_show' => [
    //                             'type' => 'integer'
    //                         ],
    //                         'is_top' => [
    //                             'type' => 'integer'
    //                         ],
    //                         'sort' => [
    //                             'type' => 'integer'
    //                         ],
    //                         'create_time' => [
    //                             'type' => 'long'
    //                         ],
    //                         'detail' => [
    //                             'type' => 'text'
    //                         ],
                        
    //                 ]
    //         ]]);
    //     } catch (\Exception $e) {
    //          json_response(0,$e->getMessage());
    //     }
   
    //  die;
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        $data   = [];
        $must   = [];
        //*ES搜索
        if(isset($search['title']) && $search['title'] != ''){
            $must[] = [
                'match' => [
                    'title' => $search['title']
                ]
            ];
        } 
        if(isset($search['detail']) && $search['detail'] != ''){
            $must[] = [
                'match' => [
                    'detail' => $search['detail']
                ]
            ];
        } 
        if(isset($search['type']) && $search['type'] != ''){
            $must[] = [
                'term' => [
                    'type' => $search['type']
                ]
            ];
        } 
        $es_client = Esearch::getEslasticInstance();
        $result = $es_client->bool_query('article',$must,[],[],$page,$limit);
        $total = 0;
        if(isset($result['hits']['total'])) $total = $result['hits']['total'];
        if(count($result['hits']['hits'])){
            $hight_light = '';
            foreach($result['hits']['hits'] as $k=> $v){
                if(isset($v['highlight']['title'][0])){
                    $hight_light = $v['highlight']['title'][0];
                    $result['hits']['hits'][$k]['_source']['title'] = $hight_light;
                }
                if(isset($v['highlight']['detail'][0])){
                    $hight_light .= $v['highlight']['detail'][0];
                    $result['hits']['hits'][$k]['_source']['title'] = $hight_light;
                }
            }
            $data = array_column($result['hits']['hits'],'_source');
        }
   
        //*普通搜索
        // if(isset($search['title']) && $search['title'] != '') $wheres[] = ['title','like',"%{$search['title']}%"];  
        // if(isset($search['type']) && $search['type'] != '')  $wheres[] = ['type','=',$search['type']];  
        // $query  = NoticeModel::with('type')->where($wheres);
        // $total  = $query->count();
        // $data   = $query->page($page, $limit)->order('sort desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }



    /**
     * 获取分类
     * @return void
     * @author Sam
     * @date 2022-04-27
     */
    public function get_type(){
        $data = NoticeType::field('id,title')->select();
        return $this->success('', $data??[]);
    }

        /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = NoticeModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }


    /**
     * 修改单个字段
     * @return void
     * @author Sam
     * @date 2022-04-27
     */
    public function notice_switch(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'field' => 'require',
                'value' => 'require',
            ], [
                'id.require'          => 'id不得为空',
                'field.require'       => '字段不得为空',
                'value.require'       => '值不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        if(NoticeModel::update([$data['field']=>$data['value']],['id'=>$data['id']])) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }
    /**
     * 设置显示
     * @return void
     * @author Sam
     * date 2021-09-29
     */
    public function is_show(){
        $id      = param_check('id');
        $checked = param_check('checked', 0);
        $res = NoticeModel::where('id', $id)->update([
            'is_show'        => $checked ? 1 : 0
        ]);
        $res ? json_response(1, '修改成功') : json_response(0, '修改失败');
    }

    /**
     * 设置置顶
     * @return bool
     * @author Sam
     * date 2021-12-09
     */
    public function is_top(){
        $id      = param_check('id');
        $checked = param_check('checked', 0);
        $res = NoticeModel::where('id', $id)->update([
            'is_top'        => $checked ? 1 : 0
        ]);
        $res ? json_response(1, '修改成功') : json_response(0, '修改失败');
    }
    
    
    /**
     * 添加
     * @return void
     * @author Sam
     * date 2021-06-04
     */
    public function create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'title' => 'require',
                'type' => 'require',
                // 'thumb' => 'require',
            ], [
                'title.require'      => '标题不得为空',
                'type.require'       => '类型不得为空',
                // 'thumb.require'      => '图片不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        try {
            $insert =  NoticeModel::create($data);
            $es_client = Esearch::getEslasticInstance();
            $es_client->insert_doc('article',$insert->id,[
                'id'     => (int)$insert->id,
                'title'  => $data['title'],
                'thumb'  => $data['thumb'],
                'is_show' => $data['is_show'],
                'is_top'  => $data['is_top'],
                'sort'   => $data['sort'],
                'type'   => $data['type'],
                'detail' => strip_tags($data['detail'])
            ]);
       
        } catch (\Exception $e) {
            json_response(0,$e->getMessage());
        }
        json_response(1,'操作成功');
    }

    /**
     * 编辑
     * @return void
     * @author Sam
     * date 2021-06-04
     */
    public function edit(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'title' => 'require',
                'type' => 'require',
                'thumb' => 'require',
            ], [
               'id.require'  => 'ID必须',
               'title.require'      => '标题不得为空',
               'type.require'       => '类型不得为空',
               'thumb.require'      => '图片不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        $info = NoticeModel::with('type')->where('id',$data['id'])->find();
        if(!$info) json_response(0,'数据不存在');
        try {
            NoticeModel::update($data,['id'=>$data['id']]);
            $es_client = Esearch::getEslasticInstance();
            $es_client->update_doc('article',$data['id'],[
                'id'     => $data['id'],
                'title'  => $data['title'],
                'thumb'  => $data['thumb'],
                'is_show' => $data['is_show'],
                'is_top'  => $data['is_top'],
                'sort'   => $data['sort'],
                'type'   => $info->type,
                'type_text' => $info->type_text,
                'detail' => strip_tags($data['detail'])
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getMessage());
        }
         
       json_response(1,'操作成功');
    }

        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-06-04
     */
    public function delete(){
  
        $data = request()->post();
        try {
            $this->validate($data, [
                'ids' => 'require',
            ], [
                'ids.require'  => 'ID必须',
            ]);
        } catch (Exception $e) {
            json_response(0,$e->getError());
        }
        $ids = explode(',',$data['ids']);
        if(!$NoticeModel = NoticeModel::where('id','in',$ids)->select()) json_response(0,'不存在');
        $es_client = Esearch::getEslasticInstance();
        foreach ($ids as $key => $value) {
           $es_client->delete_doc('article',$value);
        }
        json_response(1,'操作成功');
        // if($NoticeModel->delete()) json_response(1,'操作成功');
        // json_response(0,'操作失败');
    }

}